package io.shdxhl.simplerpc.client.spring;

import io.shdxhl.simplerpc.code.annotation.SimpleRemote;
import io.shdxhl.simplerpc.code.proxy.ProxyFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Objects;

@Slf4j
@Component
public class SimpleAnnotationProcessor implements BeanPostProcessor {


    @Autowired
    private ProxyFactory proxyFactory;


    /**
     * 在bean后置初始化上获取远程注释反射的class相关信息
     * @param bean the new bean instance
     * @param beanName the name of the bean
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Field[] fields = bean.getClass().getDeclaredFields();
        for (Field field : fields) {
            try {
                SimpleRemote annotation = field.getAnnotation(SimpleRemote.class);
                if (Objects.nonNull(annotation)) {
                    if (!field.isAccessible()) {
                        field.setAccessible(true);
                    }
                    //居于field获取注释的class
                    Class<?> type = field.getType();
                    Object proxy = proxyFactory.newProxyInstance(type);
                    if (Objects.nonNull(proxy)) {
                        field.set(bean, proxy);
                    }
                }
            } catch (IllegalAccessException e) {
               log.error("bean注释代理失败：{}", e.getMessage());
            }
        }
        return bean;
    }

}
